package com.hkyp.ss.course.provider.impl;

import com.hkyp.ss.course.apis.CommentService;
import com.hkyp.ss.course.apis.dto.common.PageReq;
import com.hkyp.ss.course.apis.dto.common.PageResp;
import com.hkyp.ss.course.apis.dto.request.CommentDTO;
import com.hkyp.ss.course.apis.dto.request.CommentLikeDTO;
import com.hkyp.ss.course.apis.dto.response.FirstCommentVO;
import com.hkyp.ss.course.apis.exception.ServiceException;
import com.hkyp.ss.course.apis.exception.UnacceptableException;
import com.hkyp.ss.course.apis.utils.BeanMapper;
import com.hkyp.ss.course.apis.utils.MyReflectionUtil;
import com.hkyp.ss.course.provider.model.Comment;
import com.hkyp.ss.course.provider.model.CourseComment;
import com.hkyp.ss.course.provider.model.Reply;
import com.hkyp.ss.course.provider.model.User;
import com.hkyp.ss.course.provider.model.mediate.UserCommLike;
import com.hkyp.ss.course.provider.repository.CommentRepository;
import com.hkyp.ss.course.provider.repository.CourCommRepository;
import com.hkyp.ss.course.provider.repository.ReplyRepository;
import com.hkyp.ss.course.provider.repository.UserRepository;
import com.hkyp.ss.course.provider.repository.mediate.UserCommLikeRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service(version = "1.0")
@Transactional(rollbackFor = Exception.class)
public class CommentServiceImpl implements CommentService {

    @Autowired
    CourCommRepository courCommRepository;

    @Autowired
    CommentRepository commentRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    UserCommLikeRepository userCommLikeRepository;

    @Autowired
    ReplyRepository replyRepository;


    // 返回评论列表页面
    @Transactional(readOnly = true)
    @Override
    public PageResp<FirstCommentVO> selectCommentToCourCommList(Long ccid, PageReq pageReq,Long userId) {

        Comment comment = new Comment();
        comment = MyReflectionUtil.byField(comment);

        comment.setCCId(ccid);

        comment.setStatus(0);

        Example<Comment> commentExample = Example.of(comment);

        Page<Comment> pageResp = commentRepository.findAll(commentExample,pageReq.toPageable());

        List<Comment> commentList = pageResp.getContent();

        // 用set可以去除重复元素
        Set<Long> fromUserIdsSet = commentList
        .stream()
        .map(Comment::getUserId)
        .collect(Collectors.toSet());

        log.info("获得的用户id为："+fromUserIdsSet);

        List<User> userList = userRepository.findAllById(fromUserIdsSet);

        // 转map
        Map<Long,User> userMap = userList
                .stream()
                .collect(Collectors.toMap(User::getId, user -> user));

        List<FirstCommentVO> firstCommentVOList = new ArrayList<>();

        commentList.forEach( comment1 -> {

            FirstCommentVO commentVO = BeanMapper.map(comment1, FirstCommentVO.class);
            commentVO.setIssueTime(comment1.getCreateAt());
            User user = userMap.get(comment1.getUserId());
            commentVO.setAvatar(user.getAvatar());
            commentVO.setUserId(user.getId());
            commentVO.setNickName(user.getNickName());
            firstCommentVOList.add(commentVO);
        });

        if(userId == null){
            return new PageResp<FirstCommentVO>(pageResp,firstCommentVOList);
        }
        // 用set可以去除重复元素
        Set<Long> commIds = commentList
                .stream()
                .map(Comment::getId)
                .collect(Collectors.toSet());
        if(!CollectionUtils.isEmpty(commIds)){
            List<UserCommLike> userCommLikes = userCommLikeRepository.findAllByUserIdAndCommIdInAndType(userId, commIds, 1);
            Set<Long> userLikedCommIds = userCommLikes
                    .stream()
                    .map(UserCommLike::getCommId)
                    .collect(Collectors.toSet());
            firstCommentVOList.forEach(dto -> {
                if(userLikedCommIds.contains(dto.getId())){
                    dto.setLiked(1);
                }
            });

        }

        return new PageResp<FirstCommentVO>(pageResp,firstCommentVOList);
    }


    public void saveComment(List courseComment){

        System.out.println(commentRepository.saveAll(courseComment));


    }

//    @Transactional(rollbackFor=Exception.class)
//    @Override
    public void addComment(Long userId,CommentDTO commentDTO) {

        Comment comment = BeanMapper.map(commentDTO, Comment.class);

        comment.setUserId(userId);
        comment.setCreateAt(System.currentTimeMillis());

        commentRepository.save(comment);

        // 添加评论成功后，给课评的评论数属性加一
        CourseComment courseComment = courCommRepository.findById(commentDTO.getCCId())
                                                          .orElseThrow(() -> new ServiceException("您要评论的课评不存在"));
        courseComment.setCommentNum(courseComment.getCommentNum()+1);
        courCommRepository.save(courseComment);

    }

    @Override
    public void addCommentOrReplyLike(Long userId, CommentLikeDTO commentLikeDTO) {


        UserCommLike userCommLike = userCommLikeRepository.findByUserIdAndCommId(userId, commentLikeDTO.getCid());

        if(commentLikeDTO.getAction() == 1){
            if(userCommLike != null){
                return;
            }
            UserCommLike userCommLike1 = new UserCommLike();
            userCommLike1.setCommId(commentLikeDTO.getCid());
            userCommLike1.setUserId(userId);
            userCommLike1.setType(commentLikeDTO.getType());
            userCommLike1.setCreateAt(System.currentTimeMillis());
            userCommLikeRepository.save(userCommLike1);

            // 对应资源赞数加一
            // type 1评论 2回复
            if(commentLikeDTO.getType()==1){
               Comment comment =  commentRepository.findById(commentLikeDTO.getCid()).orElseThrow(()->new UnacceptableException("此id的内容不存在"));
               comment.setUserLike(comment.getUserLike()+1);
               commentRepository.save(comment);
            }else if(commentLikeDTO.getType()==2){
               Reply reply =  replyRepository.findById(commentLikeDTO.getCid()).orElseThrow(()->new UnacceptableException("此id的内容不存在"));
               reply.setUserLike(reply.getUserLike()+1);
               replyRepository.save(reply);
            }

        }else if(commentLikeDTO.getAction() == 0){
            if(userCommLike == null){
                return;
            }
            userCommLikeRepository.deleteById(userCommLike.getId());
            // 对应资源赞数减一
            // type 1评论 2回复
            if(commentLikeDTO.getType()==1){
                Comment comment =  commentRepository.findById(commentLikeDTO.getCid()).orElseThrow(()->new UnacceptableException("此id的内容不存在"));
                comment.setUserLike(comment.getUserLike()-1);
                commentRepository.save(comment);
            }else if(commentLikeDTO.getType()==2){
                Reply reply =  replyRepository.findById(commentLikeDTO.getCid()).orElseThrow(()->new UnacceptableException("此id的内容不存在"));
                reply.setUserLike(reply.getUserLike()-1);
                replyRepository.save(reply);
            }
        }

    }

}
